package net.uni.util;

import java.util.Iterator;

import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

/** 
 * 处理内容:
 * hibernate 配置文件工具类
 * @version: 1.0
 * @see:net.uni.util.HibernateConfigurationHelper.java
 * @date:2012-1-12
 * @author:heweijie
 */
public class HibernateConfigurationHelper implements ApplicationContextAware{
	private static Configuration configuration;
	private String sessionFactoryBeanId;
	public void setSessionFactoryBeanId(String sessionFactoryBeanId) {
		this.sessionFactoryBeanId = sessionFactoryBeanId;
	}
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		configuration = context.getBean("&"+sessionFactoryBeanId,LocalSessionFactoryBean.class).getConfiguration();
	}
//	public void initConfiguration() {
//		configuration = GlobalSpringContext.getBean("&"+sessionFactoryBeanId,LocalSessionFactoryBean.class).getConfiguration();
//	}
	private static PersistentClass getPersistentClass(Class clazz) {
			return configuration.getClassMapping(clazz.getName());
	}
	/** 
	 * @param clazz
	 * @return
	 * @方法说明 根据实体类返回对应的数据库表明
	 * @date 2012-1-12
	 * @author heweijie
	 */
	public static String getTableName(Class clazz) {
		return getPersistentClass(clazz).getTable().getName();
	}
	/** 
	 * @param clazz
	 * @return
	 * @方法说明 根据实体类返回对应的数据库主键字段
	 * @date 2012-1-12
	 * @author heweijie
	 */
	public static String getPkColumnName(Class clazz) {
		 return getPersistentClass(clazz).getTable().getPrimaryKey()
				    .getColumn(0).getName();
	}
	
	/** 
	 * @param clazz
	 * @param propertyName
	 * @return
	 * @方法说明 通过实体类和属性，获取实体类属性对应的表字段名称
	 * @date 2012-1-12
	 * @author heweijie
	 */
	public static String getColumnName(Class clazz, String propertyName) {
		Property property =getPersistentClass(clazz).getProperty(propertyName);
		Iterator<Column> it = property.getColumnIterator();
		  if (it.hasNext()) {
		   return it.next().getName();
		  }
		  return null;
	}

}
